package com.project.collectAPI.config;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.alibaba.druid.sql.visitor.functions.Char;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.collectAPI.comm.*;

public class FilterPostRequestWrapper extends HttpServletRequestWrapper {
    /**
     * 存储body数据的容器
     */
    private byte[] body;
    private Map<String, String[]> parameterMap; // 所有参数的Map集合

    public FilterPostRequestWrapper(HttpServletRequest request) throws IOException {
        // 将request交给父类，以便于调用对应方法的时候，将其输出，其实父亲类的实现方式和第一种new的方式类似
        super(request);

        /*
        this.parameterMap.putAll(requestMap);
        this.modifyParameterValues();
        //map 转 json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(this.parameterMap);
        //json字符串 换 inputStream
        InputStream jsonStream = new ByteArrayInputStream(jsonStr.getBytes());
        String bodyStr = ins2Str(jsonStream);
        //保存输出的数据
        body = bodyStr.getBytes(Charset.forName("utf-8"));*/

        System.out.println("打印Key............");


        System.out.println("转换编码....");
        //接下来的request使用这个
        String bodyStr = inputStream2String(request.getInputStream());
        //System.out.println("...bodyStr!!!!!!!!!!!!!!!!!!!!!!!..."+bodyStr);
        body = bodyStr.getBytes(Charset.forName("utf-8"));
        //System.out.println("body数据长度"+body.length);

        System.out.println("收藏key");
        this.parameterMap= request.getParameterMap();
        Set<String> set =parameterMap.keySet();
        Iterator<String> it=set.iterator();

        while(it.hasNext()){
            String key= it.next();
            String[] values = parameterMap.get(key);
            values[0] = values[0].trim(); //解码
            System.out.println("==>:" + key + ", value==>:" +values[0]);
        }


    }


    /**
     * 将parameter的值改变后重写回去 (解码Escape后重写回去)
     */
    public void modifyParameterValues(){
        Set<String> set =parameterMap.keySet();
        Iterator<String> it=set.iterator();
        while(it.hasNext()){
            String key= it.next();
            String[] values = parameterMap.get(key);
            values[0] = values[0].trim(); //解码
            System.out.println("==>:" + key + ", value==>:" + values);
            parameterMap.put(key, values);
        }
    }


    /**
     * 获取指定参数名的值，如果有重复的参数名，则返回第一个的值 接收一般变量 ，如text类型
     *
     * @param name 指定参数名
     * @return 指定参数名的值
     */
    @Override
    public String getParameter(String name) {
        if(parameterMap.containsKey(name)){
            String[] results = parameterMap.get(name);
            return results[0];
        }
        return null;
    }


    /**
     * 获取指定参数名的所有值的数组，如：checkbox的所有数据
     * 接收数组变量 ，如checkobx类型
     */
    @Override
    public String[] getParameterValues(String name) {
        return parameterMap.get(name);
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        return parameterMap;
    }

    public void setParameterMap(Map<String, String[]> parameterMap) {
        this.parameterMap = parameterMap;
    }

    /**
     * 将inputStream里的数据读取出来并转换成字符串
     *
     * @param inputStream inputStream
     * @return String
     */
    private String ins2Str(InputStream inputStream) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
        return sb.toString();
    }



    /**
     * 将inputStream里的数据读取出来并转换成字符串
     *
     * @param inputStream inputStream
     * @return String
     */
    private String inputStream2String(InputStream inputStream) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }

        //修改数据源学生姓名
        /*JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        if (jsonObject != null && jsonObject.get("student") != null) {
            Student student = JSON.toJavaObject((JSON) jsonObject.get("student"), Student.class);
            log.info("修改之前的学生名称为：" + student.getName());
            student.setName("amd");
            jsonObject.put("student", student);
            return jsonObject.toJSONString();
        }*/

        //System.out.println("获取到数据源...."+ Escape.unescape(sb.toString()));
        //return sb.toString();
        //body = Escape.unescape(sb.toString()).getBytes(StandardCharsets.UTF_8);

        /*String ConvertEscape=Escape.unescape(sb.toString()); //解码 js escape
        JSONObject jsonObject = JSONObject.parseObject(ConvertEscape);*/

        return Escape.unescape(sb.toString());
    }



    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        System.out.println("要返回body数据长度啦~~"+body.length);
        ByteArrayInputStream bis = new ByteArrayInputStream(body);
        return new MyServletInputStream(bis);

        //final ByteArrayInputStream inputStream = new ByteArrayInputStream(body);
        //return new MyServletInputStream(bis);
        /*eturn new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return inputStream.read();
            }

            @Override
            public boolean isFinished() {
                return true;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };*/
    }
    class MyServletInputStream extends ServletInputStream{
        private ByteArrayInputStream bis;
        public MyServletInputStream(ByteArrayInputStream bis){
            this.bis=bis;
        }
        @Override
        public boolean isFinished() {
            return true;
        }
        @Override
        public boolean isReady() {
            return true;
        }
        @Override
        public void setReadListener(ReadListener listener) {
        }
        @Override
        public int read(){
            return bis.read();
        }
    }

} //Class End
